
import {InterceptorType, Interceptor, InterceptorInsOrClass} from "../core/Interceptor";
import {EasyARouter} from "../core/EasyARouter";
import {Log} from "../util/Log";
import {Controller} from "../core/Controller";
import {_} from "../util/UtilTs";
import {DefaultModule} from "../extra/DefaultModule";

const express = require('express');

export class EasyA{

    static App:EasyA;
    express:any;
    router:EasyARouter;
    setting:{
        port?:number,
        rootDir?:string,
        staticDir?:string,
        dev?:true
    } = {
        port:3000,
        rootDir : '',
        staticDir : '',
    };

    static controllers:Array<Controller> = [];
    public defaultModule: DefaultModule;


    constructor(options:Partial<EasyA>){
        EasyA.App = this;

        this.express = new express();
        _.merge(this,options);
        this.router = new EasyARouter(this);
        this.defaultModule = new DefaultModule(this);
    }

    interceptors:Array<Interceptor> = [];
    public addInterceptor = (clazz:InterceptorInsOrClass)=> Interceptor.AddInterceptorToCollection(this.interceptors,clazz,InterceptorType.flow);

    //添加默认中间件
    public startRoute(){
        Log.isDevMode = this.setting.dev;
    }

    public endRoute(){

        const app = this.express;

        //服务静态资源
        if(this.setting.staticDir){
            app.use(express.static(this.setting.staticDir));
        }
    }

    public async start() {
        let ret =  await this.express.listen(this.setting.port);
        Log.info(JSON.stringify(this.setting,null,4));
        return ret;
    }


}
